package com.carl.creatThread;


import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 实现Callable 重写call方法，配合FutureTask
 */
public class MyTest_2_3 {
    public static void main(String[] args) throws Exception {
//        //1. 创建MyCallable
//        MyCallable myCallable = new MyCallable();
//        //2. 创建FutureTask，传入Callable
//        FutureTask<Object> futureTask = new FutureTask<>(myCallable);
//        //3. 创建FutureTask，传入Callable
//        Thread thread = new Thread(futureTask);
//        //4. 启动线程
//        thread.start();
//        //5. 获取结果
//        Object o = futureTask.get();
//        System.out.println("结果为: " + o);

        //创建异步任务实现了Callable接口 具体业务
        FutureTask<Object> objectFutureTask = new FutureTask<>(() -> {
            //call方法执行的内容 也就是业务
            int count = 0;
            for (int i = 0; i < 100; i++) {
                count += i;
            }
            return count;
        });
        //创建线程把这个异步任务放进去
        Thread thread = new Thread(objectFutureTask);
        //启动线程
        thread.start();
        //获取结果
        Object o = objectFutureTask.get();
        System.out.println("总和为： " + o);
    }



    }




class MyCallable implements Callable<Object>{
    @Override
    public Object call() throws Exception {
        int count = 0;
        for (int i = 0; i < 100; i++) {
            count += i;
        }
        return count;
    }
}
